package com.herui.iot.ui.evaluation.execute;

import com.herui.device_lib.listener.DeviceLis;
import com.herui.device_lib.listener.DeviceLisAdapter;
import com.herui.device_lib.presenter.DevicePresenter;
import com.herui.device_lib.presenter.DevicePresenterInter;
import com.herui.device_lib.presenter.SimDevicePresenter;
import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sport_care.BasePresenter;
import com.herui.sport_care.config.AppConfig;
import com.herui.sport_care.data.RepositoryFactory;
import com.herui.sport_care.data.SportFileManager;
import com.herui.sport_care.data.check.BetaDataUploadForm;
import com.herui.sport_care.data.check.DeviceInfo;
import com.herui.sport_care.data.check.EvalUserInfo;
import com.herui.sport_care.data.check.EvaluationStage;
import com.herui.sport_care.data.check.UpDataInfo;
import com.herui.sport_care.data.check.source.CheckSource;
import com.herui.sport_care.data.eval.EvalInfo;
import com.herui.sport_care.data.user.UserInfo;
import com.herui.sport_care.data.user.source.UserSource;
import com.herui.sport_care.utils.DateUtils;
import com.protontek.healthy.powerbicyclesdkcore.api.PowerBicycleDataBean;
import com.protontek.healthy.sdkcore.sphygmomanometer.api.BPDataBean;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by amanda.shan on 2022/12/9.
 */
public abstract class BaseExecutePresenter implements BasePresenter {

    SimpleDateFormat format = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss");

    protected CheckSource checkSource;

    // 文件管理
    protected SportFileManager sportFileManager = new SportFileManager();

    // 阶段
    protected EvaluationStage stage;

    // 最大最小心率
    private int heart;
    protected int minHeart;
    protected int maxHeart;
    protected Long hhrTime;
    protected Long lhrTime;
    protected List<UpDataInfo> hearts = new LinkedList<UpDataInfo>();
    protected List<UpDataInfo> resistances = new LinkedList<UpDataInfo>();
    protected int maxResistance;  // 最大阻力

    // 每次血压数据
    private BPDataBean bpDataBean;
    private Long bpTime;
    // 每次血氧数据
    private Integer recoverBloodOxygen;
    private Long spoTime;

    // 恢复期
    private BPDataBean[] bpDataBeans = new BPDataBean[3];  // 血压
    // 1 2 分组心率
    private Integer recoverOneMinuteHr;
    private String recoverOneMinuteHrTime;
    private Integer recoverTwoMinuteHr;
    private String recoverTwoMinuteHrTime;

    // 评估信息
    protected EvalInfo evalInfo;
    protected EvalUserInfo evalUserInfo;
    // 被选择的心电设备 在静息的时候选择的
    protected DeviceInfo ecgDeviceInfo;
    // 被选择的踏车设备
    protected DeviceInfo treadmillDeviceInfo;

    protected DevicePresenterInter devicePresenter;

    protected Long stageStartTime;    // 大阶段的开始时间

    public BaseExecutePresenter(EvalInfo evalInfo) {
        this.evalInfo = evalInfo;
        checkSource = RepositoryFactory.getInstance().getCheckSource();

        if (AppConfig.DeviceDebug){
            devicePresenter = new SimDevicePresenter();
        }else{
            devicePresenter = new DevicePresenter();
        }
    }

    public DevicePresenterInter getDevicePresenter() {
        return devicePresenter;
    }

    public void setEvalInfo(EvalInfo evalInfo) {
        this.evalInfo = evalInfo;
    }

    public void setEvalUserInfo(EvalUserInfo evalUserInfo) {
        this.evalUserInfo = evalUserInfo;
    }

    public void setEcgDeviceInfo(DeviceInfo ecgDeviceInfo) {
        this.ecgDeviceInfo = ecgDeviceInfo;
    }

    public void setTreadmillDeviceInfo(DeviceInfo treadmillDeviceInfo) {
        this.treadmillDeviceInfo = treadmillDeviceInfo;
    }

    @Override
    public void start() {
        DeviceLisAdapter.add(baseDeviceLis);
    }

    public void stop() {
        DeviceLisAdapter.remove(baseDeviceLis);
    }

    public SportFileManager getSportFileManager() {
        return sportFileManager;
    }

    /**
     * 恢复数据处理
     */
    protected void recoverProcess(){
        // 恢复阶段
        if (stage != null && stage.equals(EvaluationStage.RECOVER)){
            // 保存心率
            if (System.currentTimeMillis()-stageStartTime >= 60000 && recoverOneMinuteHr == null){
                recoverOneMinuteHr = heart;
                recoverOneMinuteHrTime = format.format(new Date());
            }
            if (System.currentTimeMillis()-stageStartTime >= 120000 && recoverTwoMinuteHr == null){
                recoverTwoMinuteHr = heart;
                recoverTwoMinuteHrTime = format.format(new Date());
            }
        }
    }

    /**
     * 保存血压
     * @param index
     * @param bpDataBean
     */
    public void saveBp(int index, BPDataBean bpDataBean){
        bpDataBeans[index] = bpDataBean;
    }

    /**
     * 上传热身数据
     * @param isUploadAll
     */
    public void quiteDataUp(boolean isUploadAll){
        if (stage == null){
            return;
        }
        BetaDataUploadForm betaDataUploadForm = getBaseBetaDataUploadForm(isUploadAll,
                EvaluationStage.QUIESCENT);

        betaDataUploadForm.setQuiescentHr(heart);
        if (hhrTime != null){
            betaDataUploadForm.setQuiescentHighestHr(maxHeart);
            betaDataUploadForm.setQuiescentHighestHrTime(new Date(hhrTime));
        }
        if (lhrTime != null){
            betaDataUploadForm.setQuiescentLowestHr(minHeart);
            betaDataUploadForm.setQuiescentLowestHrTime(new Date(lhrTime));
        }
        if (bpTime != null){
            betaDataUploadForm.setQuiescentSbp((int) bpDataBean.getSystolicBp());
            betaDataUploadForm.setQuiescentDbp((int) bpDataBean.getDiastolicBp());
            betaDataUploadForm.setQuiescentBloodPressureTime(new Date(bpTime));
        }
        if (spoTime != null){
            betaDataUploadForm.setQuiescentBloodOxygen(recoverBloodOxygen);
            betaDataUploadForm.setQuiescentBloodOxygenTime(new Date(spoTime));
        }


        dataUpload(betaDataUploadForm);
    }

    /**
     * 上传热身数据
     * @param isUploadAll
     */
    protected void warnUpDataUp(boolean isUploadAll){
        if (stage == null){
            return;
        }
        BetaDataUploadForm betaDataUploadForm = getBaseBetaDataUploadForm(isUploadAll,
                EvaluationStage.WARM_UP);

        if (hhrTime != null){
            betaDataUploadForm.setWarmUpHighestHr(maxHeart);
            betaDataUploadForm.setWarmUpHighestHrTime(new Date(hhrTime));
        }
        if (lhrTime != null){
            betaDataUploadForm.setWarmUpLowestHr(minHeart);
            betaDataUploadForm.setWarmUpLowestHrTime(new Date(lhrTime));
        }
        if (hearts != null && hearts.size() > 0){
            int sum = 0;
            for (int i = 0; i < hearts.size(); i++) {
                sum += hearts.get(i).getValue();
            }
            int heartAgv = sum / hearts.size();
            betaDataUploadForm.setWarmUpAverageHr(heartAgv);
        }

        dataUpload(betaDataUploadForm);
    }

    /**
     * 上传测试数据
     * @param isUploadAll
     */
    protected void testDataUp(boolean isUploadAll){
        if (stage == null){
            return;
        }

        BetaDataUploadForm betaDataUploadForm = getBaseBetaDataUploadForm(isUploadAll,
                EvaluationStage.TESTING);

        if (hhrTime != null){
            betaDataUploadForm.setTestingHighestHr(maxHeart);
            betaDataUploadForm.setTestingHighestHrTime(new Date(hhrTime));
        }
        if (lhrTime != null){
            betaDataUploadForm.setTestingLowestHr(minHeart);
            betaDataUploadForm.setTestingLowestHrTime(new Date(lhrTime));
        }
        if (hearts != null && hearts.size() > 0){
            int sum = 0;
            for (int i = 0; i < hearts.size(); i++) {
                sum += hearts.get(i).getValue();
            }
            int heartAgv = sum / hearts.size();
            betaDataUploadForm.setTestingAverageHr(heartAgv);
        }

        // 运动时长testingExerciseDuration 测试中运动时长 HH:mm:ss
        int second = (int) ((System.currentTimeMillis()-stageStartTime)/1000);
        betaDataUploadForm.setTestingExerciseDuration(DateUtils.sToHHmmss(second));
        // 测试中最大阻力级别
        betaDataUploadForm.setTestingMaxResistance(maxResistance);

        dataUpload(betaDataUploadForm);
    }

    /**
     * 上传恢复阶段数据
     * @param isUploadAll
     * @return
     */
    protected void recoverDataUp(boolean isUploadAll){
        if (stage == null){
            return;
        }
        BetaDataUploadForm betaDataUploadForm = getBaseBetaDataUploadForm(isUploadAll,
                EvaluationStage.RECOVER);

        if (bpDataBeans[0] != null){
            betaDataUploadForm.setRecoverOneSbp((int) bpDataBeans[0].getSystolicBp());
            betaDataUploadForm.setRecoverOneDbp((int) bpDataBeans[0].getDiastolicBp());
        }
        if (bpDataBeans[1] != null){
            betaDataUploadForm.setRecoverTwoSbp((int) bpDataBeans[1].getSystolicBp());
            betaDataUploadForm.setRecoverTwoDbp((int) bpDataBeans[1].getDiastolicBp());
        }
        if (bpDataBeans[2] != null){
            betaDataUploadForm.setRecoverThreeSbp((int) bpDataBeans[2].getSystolicBp());
            betaDataUploadForm.setRecoverthreeDbp((int) bpDataBeans[2].getDiastolicBp());
        }

        betaDataUploadForm.setRecoverOneMinuteHr(recoverOneMinuteHr);
        betaDataUploadForm.setRecoverOneMinuteHrTime(recoverOneMinuteHrTime);
        betaDataUploadForm.setRecoverTwoMinuteHr(recoverTwoMinuteHr);
        betaDataUploadForm.setRecoverTwoMinuteHrTime(recoverTwoMinuteHrTime);

        betaDataUploadForm.setRecoverBloodOxygen(recoverBloodOxygen);

        dataUpload(betaDataUploadForm);
    }


    private BetaDataUploadForm getBaseBetaDataUploadForm(boolean isUploadAll, EvaluationStage stage){
        BetaDataUploadForm betaDataUploadForm = new BetaDataUploadForm();
        betaDataUploadForm.setStage(stage);
        betaDataUploadForm.setEvaluationSchemeId(evalInfo.getEvaluationSchemeId());
        betaDataUploadForm.setBetaSchemeId(evalInfo.getBetaSchemeId());
        betaDataUploadForm.setAgreementId(evalInfo.getAgreementId());
        betaDataUploadForm.setBeEvaluatedId(evalUserInfo.getUserId());
        betaDataUploadForm.setUploadAll(isUploadAll);

        return betaDataUploadForm;
    }

    /**
     * 上传
     * @param betaDataUploadForm
     */
    protected void dataUpload(BetaDataUploadForm betaDataUploadForm){
        UserSource userSource = RepositoryFactory.getInstance().getUserSource();
        UserInfo userInfo = userSource.getUserInfo();
        long organId = userInfo.getOrganId();

        // 被评估人
        betaDataUploadForm.setEvaluatorId(userInfo.getId());
        Boolean uploadAll = betaDataUploadForm.getUploadAll();

        checkSource.dataUpload(betaDataUploadForm, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dataUploadSucess(uploadAll);
            }

            @Override
            public void onError(Throwable e, String code, String message) {
                processError(e, code, message);
            }
        });
    }

    /**
     * 上传成功回调函数
     */
    protected void dataUploadSucess(Boolean uploadAll){

    }


    /**
     * 清除所有数据
     */
    protected void clearData(){
        maxHeart = 0;
        hhrTime = null;
        minHeart = 0;
        lhrTime = null;
        maxResistance = 0;
        hearts.clear();
        resistances.clear();
    }

    /**
     * 监听
     */
   protected DeviceLis baseDeviceLis = new DeviceLis() {
        @Override
        public void onEcgHeart(int heart) {
            if (heart < 0){
                return;
            }
            if (minHeart == 0 || minHeart > heart) {
                minHeart = heart;
                hhrTime = System.currentTimeMillis();
            }
            if (maxHeart == 0 || maxHeart < heart) {
                maxHeart = heart;
                lhrTime = System.currentTimeMillis();
            }
            hearts.add(new UpDataInfo(heart, System.currentTimeMillis()));
        }

        @Override
        public void onEcgData(byte[] bytes) {
            try {
                if (stage != null){
                    Long evaluationSchemeId = evalInfo.getEvaluationSchemeId();
                    sportFileManager.saveEcgData(evalUserInfo.getUserId().intValue(), evaluationSchemeId.intValue()
                            , bytes, stage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onReceiveSpO2(int spo) {
            recoverBloodOxygen = spo;
            spoTime = System.currentTimeMillis();
        }

        @Override
        public void onBpResult(BPDataBean bpDataBean) {
            BaseExecutePresenter.this.bpDataBean = bpDataBean;
            bpTime = System.currentTimeMillis();
        }

        @Override
        public void onReceiveData(PowerBicycleDataBean powerBicycleDataBean) {
            int r = (int) powerBicycleDataBean.getResistanceLevel();
            if (maxResistance > r){
                r = maxResistance;
            }
            resistances.add(new UpDataInfo(r, System.currentTimeMillis()));
        }
    };
}
